﻿package capricornus.components.tilelist
{
	import capricornus.components.event.ComponentsEvent;
	import capricornus.components.sprite.AbstractComponent;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.setTimeout;

	public class SimpleList extends AbstractComponent
	{
		private var container:Sprite;
		
		private var _verticalGap:int = 0;
		
		public static const CLEAR:String = "CLEAR";
		
		private var _promptResize:Boolean = false;
		
		public function SimpleList()
		{
			super();
			init();
		}
		
		private function init():void
		{
			container = new Sprite();
			addChild( container );
		}
		
		public function destroy():void
		{
			removeAll();
		}
		
		public function set promptResize( value:Boolean ):void
		{
			_promptResize = value;
		}
		
		public function set verticalGap( value:int ):void
		{
			_verticalGap = value;
			refresh();
		}
		
		public function get verticalGap():int
		{
			return _verticalGap;
		}
		
		public function get length():int
		{
			return container.numChildren;
		}
		
		public function refresh():void
		{
			var len:int = container.numChildren;
			var y:int = 0;
			for( var i:int=0; i<len; i++ )
			{
				var mc:DisplayObject = container.getChildAt(i);
				mc.y = y;
				y = y + mc.height + _verticalGap;
			}
			if( _promptResize ) dispatchEvent( new ComponentsEvent( ComponentsEvent.RESIZE ) );
		}
		
		private function onResize( e:ComponentsEvent ):void
		{
			refresh();
		}
		
		public function addItem( child:DisplayObject ):DisplayObject
		{
			var yn:Number = container.height;
			container.addChild( child );
			child.y = yn + (yn > 0 ? _verticalGap : 0);
			
			return child;
		}
		
		public function addItemAt( child:DisplayObject, index:int ):DisplayObject
		{
			container.addChildAt( child, index );

			refresh();
			
			return child;
		}
		
		public function getItemAt( index:int ):DisplayObject
		{
			if( index < container.numChildren )
			{
				return container.getChildAt( index );
			}
			return null;
		}
		
		public function removeItem( item:DisplayObject ):DisplayObject
		{
			return container.removeChild( item );
		}
		
		public function removeAll():void
		{
			while( container.numChildren > 0 )
			{
				container.removeChildAt( 0 );
			}
			container.y = 0;
			dispatchEvent( new Event( CLEAR ) );
		}
		
		public function removeAllSlowly():void
		{
			if( container.numChildren > 0 )
			{
				container.removeChildAt( container.numChildren-1 );
				setTimeout( removeAllSlowly, 20 );
			}
			else
			{
				dispatchEvent( new Event( CLEAR ) );
			}
		}
	}
}












